import os
import re
from lxml import etree as ET


def covert_text(input_file_path, output_file_path):
    tree = ET.parse(input_file_path)
    root = tree.getroot()
    namespace = {'kml': 'http://www.opengis.net/kml/2.2', 'gx': 'http://www.google.com/kml/ext/2.2'}
    # 找到所有的 <gx:Track> 标签
    placemarks = root.findall('.//kml:Placemark', namespace)
    for placemark in placemarks:
        lineStrings = placemark.findall('.//kml:LineString', namespace)
        if lineStrings is not None and len(lineStrings) > 0:
            for lineString in lineStrings:
                coordinates = lineString.findall('.//kml:coordinates', namespace)
                if coordinates is not None:
                    for coordinate in coordinates:
                        words = re.split(r'\s+', coordinate.text)
                        # 反转轨迹点
                        reverse_words = words[::-1]
                        # 反转后的字符串
                        reverse_str = ' '.join(map(str, reverse_words))
                        # 反转字符串
                        coordinate.text = reverse_str
                        print(coordinate.text)
        else:
            gx_tracks = placemark.findall('.//gx:Track', namespaces=namespace)
            if gx_tracks is not None and len(gx_tracks) > 0:
                for gx_track in gx_tracks:
                    sting_track = []
                    linestring = ET.Element('LineString')
                    coordinates = ET.Element('coordinates')
                    linestring.insert(0, coordinates)

                    gx_coords = gx_track.findall('gx:coord', namespaces=namespace)
                    if gx_coords is not None and len(gx_coords) > 0:
                        for gx_coord in gx_coords:
                            text = gx_coord.text.replace(' ', ',')
                            sting_track.append(text)
                        # print(sting_track)
                        # 反转轨迹点
                        reverse_words = sting_track[::-1]
                        # 反转后的字符串
                        reverse_str = ' '.join(map(str, reverse_words))
                        coordinates.text = reverse_str
                        parent = gx_track.getparent()
                        parent.replace(gx_track, linestring)
                        # print(coordinates.text)
    # 互换起点
    start_point_coord = root.find('.//kml:Placemark[@id="startPoint"]//kml:coordinates', namespaces=namespace)
    end_point_coord = root.find('.//kml:Placemark[@id="endPoint"]//kml:coordinates', namespaces=namespace)
    if start_point_coord is not None and end_point_coord is not None:
        # 交换 <coordinates> 的内容
        start_coord_text = start_point_coord.text
        end_coord_text = end_point_coord.text

        start_point_coord.text = end_coord_text
        end_point_coord.text = start_coord_text
    tree.write(output_file_path, pretty_print=True, xml_declaration=True, encoding='utf-8')


dirname = os.path.dirname(__file__)

test_data_dir = os.path.join(dirname, 'test_data')
input_file_path = os.path.join(test_data_dir, '三城连穿｜小红帽.kml')
output_file_path = os.path.join(test_data_dir, 'reverse_三城连穿｜小红帽.kml')

covert_text(input_file_path, output_file_path)
